package daosimpl;

import java.util.ArrayList;
import java.util.List;

import model.Curso;
import model.Permiso;
import model.Profesor;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Transaction;

import util.HibernateUtil;
import daos.PermisoDAO;

public class PermisoDAOImplH implements PermisoDAO {
	
	private Transaction tx;
	
	@Override
	public void insertarPermiso(Permiso p) throws HibernateException {

		try {
			
			tx = HibernateUtil.session.beginTransaction();
			HibernateUtil.session.save(p);
			tx.commit();
			if (!tx.wasCommitted()){
			    tx.commit();
			}
			System.out.println("Permiso !! "+p.toString());
			
		} catch (Exception he) {
			System.out.println("mall " + he.getMessage() + he.getCause());
			tx.rollback(); 
		} finally { 
            //session.close(); 
        }  
		
	}
	
	@Override
	public List<Permiso> FindById(Profesor p) throws HibernateException {
		List<Permiso> result = new ArrayList<Permiso>();
		try {
			
			tx = HibernateUtil.session.beginTransaction();
						
			Query query = HibernateUtil.session
					.createQuery("FROM Permiso where docente_id = '"+
			p.getDocenteId() +"'");
			result = query.list();
			System.out.println(query.list());
			System.out.println(query.list().size());
			if (query.list().isEmpty()) {
				System.out.println("esta vacio");
			}
			tx.commit();
			if (!tx.wasCommitted()){
			    tx.commit();
			}			
			return result;
			
		} catch (Exception he) {
			System.out.println("mall " + he.getMessage() + he.getCause());
			tx.rollback(); 
		} finally { 
            //session.close(); 
        }  
		return result; 
	}
	
	@Override
	public int obtenerId() throws HibernateException {
		int id = 0;
		List<Permiso> result = new ArrayList<Permiso>();
		try {
			
			tx = HibernateUtil.session.beginTransaction();
						
			Query query = HibernateUtil.session
					.createQuery("FROM Permiso");
			result = query.list();
			System.out.println(query.list());
			System.out.println(query.list().size());
			if (!query.list().isEmpty()) {
				id=	result.get(result.size()-1).getIdPermiso();  
			}
			id++;
			tx.commit();
			if (!tx.wasCommitted()){
			    tx.commit();
			}			
			return id;
			
		} catch (Exception he) {
			System.out.println("mall " + he.getMessage() + he.getCause());
			tx.rollback(); 
		} finally { 
            //session.close(); 
        }  
		return id;
	}

}
